package com.pdweb.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.pdweb.dao.CargosDao;
import com.pdweb.dao.DivisoesDao;
import com.pdweb.dao.TurnosDao;
import com.pdweb.vo.Cargos;
import com.pdweb.vo.Divisoes;
import com.pdweb.vo.Turnos;

/**
 * Servlet implementation class FuncionariosCadastroServlet
 */
@WebServlet("/FuncionariosCadastroServlet")
public class FuncionariosCadastroServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public FuncionariosCadastroServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doService(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		doService(request, response);

	}

	protected void doService(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		try {

			// verifica se existe divisao cadastrada

			int empresaId = Integer.parseInt(request
					.getParameter("empresas_ID_EMPRESA_emp"));

			DivisoesDao divisoesDao = new DivisoesDao();

			boolean teste = divisoesDao.verificaDivisao(empresaId);

			if (teste == false) { // verifica se empresa tem divisoes cadastradas

				request.setAttribute("divisaoVazia", "divisao vazia");
				
				getServletContext().getRequestDispatcher(
						"/cadastro_funcionario.jsp").forward(request, response);
				
			} else {

				// lista turno

				TurnosDao turnosDao = new TurnosDao();

				List<Turnos> turno = turnosDao.obterTurnos();

				request.setAttribute("turnos", turno);

				// lista divisao

				String sql = "select * from divisoes where empresas_ID_EMPRESA_emp = "
						+ empresaId + ";";

				List<Divisoes> divisoes = divisoesDao.listaDivisoesPorEmpresa(sql);

				request.setAttribute("divisao", divisoes);

				// lista cargo

				CargosDao cargosDao = new CargosDao();

				List<Cargos> cargo = cargosDao.obterCargos();

				request.setAttribute("cargos", cargo);

				getServletContext().getRequestDispatcher("/cadastro_funcionario.jsp").forward(request, response);

			}

		} catch (ClassNotFoundException e) {

			e.printStackTrace();
		} catch (SQLException e) {

			e.printStackTrace();
		}
	}

}
